package ink.tsg.javabase.mergeTwoLists;

public class MergeTwoListTest {

    public static void main(String[] args) {
        ListNode list1 = new ListNode(1);
        list1.next = new ListNode(2);
        list1.next.next = new ListNode(4);

        ListNode list2 = new ListNode(1);
        list2.next = new ListNode(3);
        list2.next.next= new ListNode(4);

        System.out.println(mergeTwoLists1(list1, list2));


    }
    public static ListNode mergeTwoLists1(ListNode list1, ListNode list2) {

        while(list1!=null&&list2!=null){
            if(list1.val<list2.val){
                ListNode temp = list1.next;
                list1.next = list2;
                list1 = temp;
            }else{
                ListNode temp = list2.next;
                list2.next = list1;
                list2 = temp;
            }
        }

        return list1==null?list2:list1;
    }
        public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1==null){
            return list2;
        }
        if(list2 == null){
            return list1;
        }
        ListNode  head = list1.val>list2.val?list2:list1;
        ListNode p = list1;
        while(list2!=null){
            ListNode temp;
            if(p.val >list2.val){
                temp = list2.next;
                list2.next = p;
                list2 = temp;
            }else{
                temp = p.next;
                p.next = list2;
                p = list2;
                list2 = temp;
            }

        }
        return head;
    }
}
